//
//  ShoppingCartViewController.m
//  YunGou
//
//  Created by macbook on 16/5/16.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "ShoppingCartViewController.h"
#import "PayMoneyViewController.h"
#import "GoodsDetailViewController.h"
#import "RootTableView.h"
#import "ShoppingCartCell.h"
#import "ProductModel.h"
#import "NullDataView.h"
#import <MJRefresh.h>

@interface ShoppingCartViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet RootTableView *tableView;
@property (nonatomic,strong) UIView *bgView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (weak, nonatomic) IBOutlet UILabel *goodsNumLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (nonatomic,assign) NSInteger totalPrice;
@property (nonatomic,strong) NullDataView *nullDataView;
@end

@implementation ShoppingCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealKeyboardShow) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealKeyboardHide) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeShopCartNum:) name:@"ChangeShopCarNum" object:nil];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadData];
    }];
    
}

- (void)changeShopCartNum:(NSNotification *)notifi{
    NSDictionary *userInfo = notifi.userInfo;
    NSInteger substractNum = [userInfo[@"subtractNum"] integerValue];
    _totalPrice += substractNum;
    _priceLabel.text = [NSString stringWithFormat:@"%ld元",_totalPrice];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadData];
}

- (void)loadData{
    _dataArray = [NSMutableArray array];
    _totalPrice = 0;
    [NetWorkTool shopCartListWithSuceess:^(id object) {
        if ([object[@"code"] integerValue] == 1) {
            for (NSDictionary *dict in object[@"data"]) {
                ProductModel *model = [ProductModel modelWithDict:dict];
                [_dataArray addObject:model];
            }
        }
        
        if (_dataArray.count == 0) {
            [self.tableView addSubview:self.nullDataView];
        }else{
            if(_nullDataView){
                [_nullDataView removeFromSuperview];
                _nullDataView = nil;
            }
        }
        
        _goodsNumLabel.text = [NSString stringWithFormat:@"共%ld件商品，总计：",_dataArray.count];
        for (ProductModel *model in _dataArray) {
            _totalPrice += model.goods_num;
        }
        _priceLabel.text = [NSString stringWithFormat:@"%ld元",_totalPrice];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        
    }];

}

- (void)dealKeyboardShow{
    [self.view addSubview:self.bgView];
}

- (void)dealKeyboardHide{
    [self.bgView removeFromSuperview];
    self.bgView = nil;
    [self.view endEditing:NO];
}

//去结算
- (IBAction)payMoneyClick:(id)sender {
    PayMoneyViewController *payMoneyVC = SB(@"ShoppingCart", @"PayMoneyVC");
    if (_dataArray.count == 0) {
        [MBProgressHUD showError:@"购物车为空哦"];
        return;
    }
    payMoneyVC.orderArray = _dataArray;
    [NetWorkTool balanceAccountWithSuccess:^(id object) {
        if ([object[@"code"] integerValue] == 1) {
            payMoneyVC.orderId = object[@"data"];
        }
    } failure:^(NSError *error) {
        
    }];
    [self.navigationController pushViewController:payMoneyVC animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShoppingCartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (_dataArray.count != 0) {
        cell.productModel = _dataArray[indexPath.row];
    }
    cell.block = ^(ProductModel *model){
        GoodsDetailViewController *goodsDetailVC = SB(@"Common", @"GoodsDetailVC");
        goodsDetailVC.detailType = DonotAnnounce;
        goodsDetailVC.productModel = model;
        [self.navigationController pushViewController:goodsDetailVC animated:YES];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 105;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        ProductModel *productModel = _dataArray[indexPath.row];
        [NetWorkTool deleteShopCartWithGoodsId:productModel.Id success:^(id object) {
            if ([object[@"code"] integerValue] == 1) {
                [MBProgressHUD showSuccess:@"删除成功"];
                [_dataArray removeObject:productModel];
                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                _goodsNumLabel.text = [NSString stringWithFormat:@"共%ld件商品，总计：",_dataArray.count];
                _totalPrice -= productModel.goods_num;
                _priceLabel.text = [NSString stringWithFormat:@"%ld元",_totalPrice];
                if (_dataArray.count == 0) {
                    [self.tableView addSubview:self.nullDataView];
                }
            }else{
                [MBProgressHUD showError:@"删除失败"];
            }
        } failure:^(NSError *error) {
            
        }];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

#pragma -mark 懒加载相关
- (UIView *)bgView{
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:self.view.bounds];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenKeyBoard)];
        [_bgView addGestureRecognizer:tap];
    }
    return _bgView;
}

- (NullDataView *)nullDataView{
    if (!_nullDataView) {
        _nullDataView = [NullDataView nullDataView];
        _nullDataView.frame = self.tableView.bounds;
    }
    return _nullDataView;
}

- (void)hiddenKeyBoard{
    [self.view endEditing:YES];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
